#!/bin/bash

#
# Copyright (c) 2021, Mangdang Technology Co., Limited
#
IO_MAP_P1=(
19 1  #servo 1
26 1  #servo 2
16 0  #buzzer
)

IO_MAP_MP=(
25 1  #servo 1
21 1  #servo 2
)

function io_init_p1(){
	len=${#IO_MAP_P1[@]}
	for((i=0;i<len;i+=2))
	do
		io=${IO_MAP_P1[i]}
		val=${IO_MAP_P1[i+1]}
		echo $io > /sys/class/gpio/export
		echo out > /sys/class/gpio/gpio$io/direction
		echo $val > /sys/class/gpio/gpio$io/value
	done
}

function io_init_mp(){
	len=${#IO_MAP_MP[@]}
	for((i=0;i<len;i+=2))
	do
		io=${IO_MAP_MP[i]}
		val=${IO_MAP_MP[i+1]}
		echo $io > /sys/class/gpio/export
		echo out > /sys/class/gpio/gpio$io/direction
		echo $val > /sys/class/gpio/gpio$io/value
	done
}

#init IO
hw_version=`cat /home/ubuntu/.hw_version`
if [ "$hw_version" == "P1" ]; then
	io_init_p1
else
	io_init_mp
fi
sleep 1

#Power monitor
while true
do
	current_voltage=`cat /sys/class/power_supply/max1720x_battery/voltage_now`
	if [ $current_voltage -le 6500 ]; then
		if [ "$hw_version" == "P1" ]; then
			echo 0 > /sys/class/gpio/gpio19/value
			echo 0 > /sys/class/gpio/gpio26/value
			echo 1 > /sys/class/gpio/gpio16/value
		else
			echo 0 > /sys/class/gpio/gpio25/value
			echo 0 > /sys/class/gpio/gpio21/value
			su ubuntu -l -c "gsp-play-1.0 /home/ubuntu/Music/low_power.mp3"
		fi
	fi
	sleep 8
done
